package net.wicp.tams.common.os.pool;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import net.wicp.tams.common.Conf;
import net.wicp.tams.common.os.SSHAssit;

public class SSHFactory implements PooledObjectFactory<SSHConnection> {

	private final String hostname;
	private final int port;
	private final String username;
	private final String password;

	public SSHFactory(String hostname, int port, String username, String password) {
		this.hostname = hostname;
		this.username = username;
		this.password = password;
		this.port = port;
	}

	public SSHFactory(String hostname, String username, String password) {
		this(hostname, Conf.getInt("common.os.ssh.port"), username, password);
	}

	public SSHFactory(String hostname, String password) {
		this(hostname, Conf.getInt("common.os.ssh.port"), "root", password);
	}

	@Override
	public PooledObject<SSHConnection> makeObject() throws Exception {
		SSHConnection conn = SSHAssit.getConn(hostname, port, username, password);
		return new DefaultPooledObject<SSHConnection>(conn);
	}

	@Override
	public void destroyObject(PooledObject<SSHConnection> p) throws Exception {
		SSHConnection conn = p.getObject();
		conn.close();
	}

	@Override
	public boolean validateObject(PooledObject<SSHConnection> p) {
		SSHConnection conn = p.getObject();
		return !conn.isConnClose();
	}

	@Override
	public void activateObject(PooledObject<SSHConnection> p) throws Exception {
		// 激活初始化
	}

	@Override
	public void passivateObject(PooledObject<SSHConnection> p) throws Exception {
		// 纯化
	}

}
